#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <sys/un.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/socket.h>

int main(int argc, char **argv)
{
    int fd, len, err;
    struct sockaddr_un un;
    char str[20];

    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        perror("socket error");
        return 1;
    }




    memset(&un, 0, sizeof(un));
    un.sun_family = AF_UNIX;
    sprintf(un.sun_path, "%05d", getpid());

    len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
    unlink(un.sun_path);
    if (bind(fd, (struct sockaddr *)&un, len) < 0) {
        perror("bind error");
        goto fail;
    }		

    memset(&un, 0, sizeof(un));
    un.sun_family = AF_UNIX;
    strcpy(un.sun_path, (char*)"foo.socket");
    len = offsetof(struct sockaddr_un, sun_path) 
        + strlen((char*)"foo.socket");

    if (connect(fd, (struct sockaddr *)&un, len) < 0) {
        perror("connect error");
        goto fail;
    }

    while(1) {
        memset(str, 0, sizeof(str));
        printf("Wait inputing....\n");
        scanf("%s", str);

        if (write(fd, str, strlen(str)) < 0) {
            perror("write error");
            goto fail;
        } else {
            printf("str: %s, len: %d\n", str, strlen(str));
        }
    }
    close(fd);

    return 0;

fail:
    close(fd);
    return 1;
}
